﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eDoc.BO;
using System.IO;
using Brettle.Web.NeatUpload;
using System.Data;
using System.Drawing;

namespace eDoc.Controls.App
{
    public partial class ucNeatUpload : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDDL();
            }
        }

        private void BindDDL()
        {
            DataTable dt = new DataTable();
            dt = BO.Data.Select_AppMode();
            ddlAppMode.DataValueField = "ID";
            ddlAppMode.DataTextField = "Mode_Name";
            ddlAppMode.DataSource = dt;
            ddlAppMode.DataBind();
            
        }

        protected void btUpload_Click(object sender, EventArgs e)
        {
            lblNote.Text = "";
            if (ddlAppMode.SelectedValue == "0")
            {
                lblNote.Text = "Bạn chưa chọn nhân viên được sử dụng ứng dụng này!";
                ddlAppMode.Focus();
                myProgressBar.Visible = false;
            }
            else
            {
                if(!CheckImage())
                {
                    lblNote.Text = "Bạn nhập sai định dạng ảnh!";
                    return;
                }

                if (uploadIPA.HasFile)
                {
                    // Tao guid de sinh ra ten file moi
                    string fileNameGuid = Guid.NewGuid().ToString().Replace("-", "");

                    btUpload.Enabled = false;
                    myProgressBar.Visible = true;
                    string fileName = uploadIPA.FileName.Replace(" ", "").ToLower();

                    if (Common.Unicode.CheckUnicode(fileName))
                        fileName = Common.Unicode.UnicodeToKoDau(fileName).ToLower();

                    string fileNameNoExt = fileName.Substring(0, fileName.IndexOf(".ipa"));
                    //string fileNameNoExt = fileNameGuid;
                    string extension = fileName.Substring(fileName.Length - 3);
                    string folderFileNew = fileNameNoExt;

                    if (extension == "ipa")
                    {
                        string folderSaveIPA = Server.MapPath(Common.folderIPA) + fileNameNoExt;
                        int i = 2;
                        string folderSaveIPANew = "";

                        if (Directory.Exists(folderSaveIPA))
                        {
                            folderSaveIPANew = folderSaveIPA + "_" + i;
                            folderFileNew = fileNameNoExt + "_" + i;
                            while (Directory.Exists(folderSaveIPANew))
                            {
                                i++;
                                folderSaveIPANew = folderSaveIPA + "_" + i;
                                folderFileNew = fileNameNoExt + "_" + i;
                            }
                            Directory.CreateDirectory(folderSaveIPANew);
                            folderSaveIPA = folderSaveIPANew;
                        }
                        else
                        {
                            Directory.CreateDirectory(folderSaveIPA);
                        }                      
                        
                        if (Directory.Exists(folderSaveIPA))
                        {
                            Directory.CreateDirectory(folderSaveIPA);
                        }
                        string fileUpload = folderSaveIPA + "\\" + fileNameGuid + ".ipa";
                       
                        //uploadIPA.MoveTo(folderSaveIPA + "\\" + fileName, MoveToOptions.Overwrite);
                        uploadIPA.MoveTo(fileUpload, MoveToOptions.Overwrite);
                        uploadIPA.Dispose();

                        string imageUrlLager = "", imageUrlSmall="";

                        int uploadImage = UploadImage(Common.folderIPA.Replace("\\", "/") + folderFileNew, ref imageUrlLager, ref imageUrlSmall);
                        if(uploadImage==2)
                        {
                            lblNote.Text = "Không đúng định dạng ảnh!";
                            return;
                        }
                        else
                        {
                            bool sucuss = ProcessFileIPA(fileUpload, fileNameGuid, folderFileNew, (int)uploadIPA.FileContent.Length, Convert.ToBoolean(ddlStatus.SelectedValue), imageUrlLager, fileNameNoExt);
                            if (sucuss)
                            {
                                btUpload.Enabled = true;
                                lblNote.Text = "Upload thành công!";
                            }
                        }                       
                    }
                    else
                    {
                        lblNote.Text = "Bạn chọn không đúng file!";
                        return;
                    }

                }
                else
                {
                    lblNote.Text = "Bạn chưa chọn file upload!";
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileUpload"></param>
        /// <param name="fileName"></param>
        /// <param name="folderFile"></param>
        /// <param name="fileSize"></param>
        /// <param name="isPublished"></param>       
        /// <returns></returns>
        private bool ProcessFileIPA(string fileUpload, string fileName, string folderFile,  int fileSize, bool isPublished, string imageUrl)
        {
            bool result = false;
            #region Extract File info.plist
            Global.log.Info("[ProcessFile] [Start Extract File Info.plist] :: " + fileUpload);
            bool flag = Common.ExtractIPA(fileUpload, Server.MapPath(Common.folderUnrar));
            string filePlistEncode = "";
            if (flag)
                filePlistEncode = Common.GetPathFileInfoPlist(fileUpload);
            Global.log.Info("[ProcessFile] [End Extract File Info.plist] :: " + filePlistEncode);
            #endregion

            if (filePlistEncode != "")
            {
                #region Decode File Plist
                Global.log.Info("[ProcessFile] [Start Decode File Info.plist] :: " + filePlistEncode);
               
                string folderDeCodePlist = Server.MapPath(Common.folderPlist) + folderFile + "\\";
                string folderEndocePlist = Server.MapPath(Common.folderUnrar) + filePlistEncode.Replace("/", "\\");
                folderDeCodePlist = folderDeCodePlist.ToLower();
                folderEndocePlist = folderEndocePlist.ToLower();
                if (!Directory.Exists(folderDeCodePlist))
                    Directory.CreateDirectory(folderDeCodePlist);

                // start doc ExpirationDate trong embedded.mobileprovision
                string fileRootEmbed = Server.MapPath(Common.folderUnrar) + filePlistEncode.Replace("/", "\\").Replace("Info.plist","") + "embedded.mobileprovision";
                string strExpirationDate = ReturnExpirationDate(fileRootEmbed);
                
                strExpirationDate = strExpirationDate.Replace("\t", "");

                strExpirationDate = strExpirationDate.Replace("<date>", "").Replace("</date>", "");

                DateTime expirationDate = DateTime.Now.AddYears(1);

                if(!string.IsNullOrEmpty(strExpirationDate))
                {
                    expirationDate = Convert.ToDateTime(strExpirationDate);
                }
                // end
                string strFileInfoPlist = Common.Plist.ConvertSavePlist(folderEndocePlist, folderDeCodePlist, fileName).ToLower();

                Global.log.Info("[ProcessFile] [End Decode File Info.plist] :: " + strFileInfoPlist);
                #endregion

                #region Create info.plist
                Global.log.Info("[ProcessFile] [Start Create File Info.plist] :: " + strFileInfoPlist);

                string folderSavePlist = "", urlInstall = "";

                string pathFilePlist = strFileInfoPlist;
                folderSavePlist = Server.MapPath(Common.folderInfo) + folderFile + "\\";
                urlInstall = Common.folderIPA.Replace("\\", "/") + folderFile + "/" + fileName + ".ipa";

                folderSavePlist = folderSavePlist.ToLower();
                urlInstall = urlInstall.ToLower();
                /*
                Common.Plist.ReadSavePlist(pathFilePlist, folderSavePlist, urlInstall, fileSize, fileName, folderFile, Convert.ToInt32(ddlAppMode.SelectedValue), txtMoTa.Text, isPublished, Convert.ToBoolean(chkJB.Checked));
                */
                Common.Plist.InsertAppList(pathFilePlist, folderSavePlist, urlInstall, fileSize, fileName, folderFile, Convert.ToInt32(ddlAppMode.SelectedValue), txtMoTa.Text, isPublished, Convert.ToBoolean(chkJB.Checked), imageUrl, expirationDate);

                Global.log.Info("[ProcessFile] [End Create File Info.plist] :: [Folder Info.plist] : " + folderSavePlist + " :: [Url Install] :: " + urlInstall);

                result = true;
                #endregion
            }


            return result;

        }

        /// <summary>
        /// Xử lý ipa up len, tạo thông tin, file plist
        /// </summary>
        /// <param name="fileUpload">Duong dan file upload</param>
        /// <param name="fileName">Ten file sau khi chuyen thanh guid</param>
        /// <param name="folderFile">Folder ipa can luu</param>
        /// <param name="fileSize"></param>
        /// <param name="isPublished"></param>
        /// <param name="imageUrl"></param>
        /// <param name="titleApp">Ten cua app</param>
        /// <returns></returns>
        private bool ProcessFileIPA(string fileUpload, string fileName, string folderFile, int fileSize, bool isPublished, string imageUrl, string titleApp)
        {
            bool result = false;
            #region Extract File info.plist
            Global.log.Info("[ProcessFile] [Start Extract File Info.plist] :: " + fileUpload);
            bool flag = Common.ExtractIPA(fileUpload, Server.MapPath(Common.folderUnrar));
            string filePlistEncode = "";
            if (flag)
                filePlistEncode = Common.GetPathFileInfoPlist(fileUpload);
            Global.log.Info("[ProcessFile] [End Extract File Info.plist] :: " + filePlistEncode);
            #endregion

            if (filePlistEncode != "")
            {
                #region Decode File Plist
                Global.log.Info("[ProcessFile] [Start Decode File Info.plist] :: " + filePlistEncode);

                string folderDeCodePlist = Server.MapPath(Common.folderPlist) + folderFile + "\\";
                string folderEndocePlist = Server.MapPath(Common.folderUnrar) + filePlistEncode.Replace("/", "\\");
                folderDeCodePlist = folderDeCodePlist.ToLower();
                folderEndocePlist = folderEndocePlist.ToLower();
                if (!Directory.Exists(folderDeCodePlist))
                    Directory.CreateDirectory(folderDeCodePlist);

                // start doc ExpirationDate trong embedded.mobileprovision
                string fileRootEmbed = Server.MapPath(Common.folderUnrar) + filePlistEncode.Replace("/", "\\").Replace("Info.plist", "") + "embedded.mobileprovision";
                string strExpirationDate = ReturnExpirationDate(fileRootEmbed);

                strExpirationDate = strExpirationDate.Replace("\t", "");

                strExpirationDate = strExpirationDate.Replace("<date>", "").Replace("</date>", "");

                DateTime expirationDate = DateTime.Now.AddYears(1);

                if (!string.IsNullOrEmpty(strExpirationDate))
                {
                    expirationDate = Convert.ToDateTime(strExpirationDate);
                }
                // end
                string strFileInfoPlist = Common.Plist.ConvertSavePlist(folderEndocePlist, folderDeCodePlist, fileName).ToLower();

                Global.log.Info("[ProcessFile] [End Decode File Info.plist] :: " + strFileInfoPlist);
                #endregion

                #region Create info.plist
                Global.log.Info("[ProcessFile] [Start Create File Info.plist] :: " + strFileInfoPlist);

                string folderSavePlist = "", urlInstall = "";

                string pathFilePlist = strFileInfoPlist;
                folderSavePlist = Server.MapPath(Common.folderInfo) + folderFile + "\\";
                urlInstall = Common.folderIPA.Replace("\\", "/") + folderFile + "/" + fileName + ".ipa";

                folderSavePlist = folderSavePlist.ToLower();
                urlInstall = urlInstall.ToLower();
                /*
                Common.Plist.ReadSavePlist(pathFilePlist, folderSavePlist, urlInstall, fileSize, fileName, folderFile, Convert.ToInt32(ddlAppMode.SelectedValue), txtMoTa.Text, isPublished, Convert.ToBoolean(chkJB.Checked));
                */
                Common.Plist.InsertAppList(pathFilePlist, folderSavePlist, urlInstall, fileSize, fileName, folderFile, Convert.ToInt32(ddlAppMode.SelectedValue), txtMoTa.Text, isPublished, Convert.ToBoolean(chkJB.Checked), imageUrl, expirationDate);

                Global.log.Info("[ProcessFile] [End Create File Info.plist] :: [Folder Info.plist] : " + folderSavePlist + " :: [Url Install] :: " + urlInstall);

                result = true;
                #endregion
            }


            return result;

        }

        private string ReturnExpirationDate(string fileRootEmbed)
        {
            string result = "";
            string[] lines = System.IO.File.ReadAllLines(fileRootEmbed);

            for (int i = 0; i < lines.Length;i++ )
            {
                if (lines[i].Contains("<key>ExpirationDate</key>"))
                {
                    return lines[i + 1];
                }
            }

            return result;
        }

        /// <summary>
        /// Gia tri tra ve = 0 : upload anh ok, = 1 : khong co anh; = 2: sai dinh dang anh 
        /// </summary>
        /// <param name="pathUrl"></param>
        /// <param name="imageUrl"></param>
        /// <returns></returns>
        private int UploadImage(string pathUrl, ref string imageUrl)
        {

            int result = 1;

            string fileName = "";

            if (string.IsNullOrEmpty(flImage.FileName))
            {
                return result;
            }

            fileName = flImage.FileName.Replace(" ", "").ToLower();

            if (Common.Unicode.CheckUnicode(fileName))
                fileName = Common.Unicode.UnicodeToKoDau(fileName).ToLower();

            if (fileName.EndsWith(".png") || fileName.EndsWith(".jpg") || fileName.EndsWith(".jpeg") || fileName.EndsWith(".gif"))
            {

                imageUrl = pathUrl + "/" + fileName;

                flImage.SaveAs(MapPath(imageUrl));

                result = 0;
            }
            else
            {
                result = 2;
            }
            return result;
        }

        private int UploadImage(string pathUrl, ref string imageUrlLager, ref string imageUrlSmall)
        {

            int result = 1;

            string fileNameLager = "";

            if (string.IsNullOrEmpty(flImage.FileName))
            {
                return result;
            }
            

            fileNameLager = flImage.FileName.Replace(" ", "").ToLower();

            if (Common.Unicode.CheckUnicode(fileNameLager))
                fileNameLager = Common.Unicode.UnicodeToKoDau(fileNameLager).ToLower();

            if (fileNameLager.EndsWith(".png"))
            {

                imageUrlLager = pathUrl + "/" + fileNameLager;
                imageUrlSmall = pathUrl + "/" + fileNameLager.Substring(0, fileNameLager.IndexOf(".png")) + "_57.png";

                flImage.SaveAs(MapPath(imageUrlLager));

                System.Drawing.Image imgInput = System.Drawing.Image.FromFile(MapPath(imageUrlLager));
                using (var resized = System.Common.ImageUtilities.ResizeImage(imgInput, 57, 57))
                {
                    //save the resized image as a jpeg with a quality of 90
                    System.Common.ImageUtilities.SaveJpeg(MapPath(imageUrlSmall), resized, 90);
                }
                //Bitmap img = new Bitmap(MapPath(imageUrlLager));
                //ImageHelper imgHelper = new ImageHelper();
                //imgHelper.Save(img, 57, 57, 90, MapPath(imageUrlSmall));

                result = 0;

            }
            else
            {
                result = 2;
            }
            return result;
        }

        private bool CheckImage()
        {
            bool flag = true;
            if(!string.IsNullOrEmpty(flImage.FileName))
            {
                string fileName = flImage.FileName;
                if (fileName.EndsWith(".png") || fileName.EndsWith(".jpg") || fileName.EndsWith(".jpeg") || fileName.EndsWith(".gif"))
                {
                    flag = true;
                }
                else
                {
                    flag = false;
                }
            }

            return flag;
        }
        
    }
}